package com.briup.corejava.day16;

/**
 * 线程安全问题：多个窗口同时售卖50张票
 */
public class Test4 {
    public static void main(String[] args) {
        Runnable r = new TicketTask();
        Thread t1 = new Thread(r,"1号窗口");
        Thread t2 = new Thread(r,"2号窗口");
        Thread t3 = new Thread(r,"3号窗口");
        Thread t4 = new Thread(r,"4号窗口");

        t2.start();
        t1.start();
        t3.start();
        t4.start();
    }
}
// 定义卖票的任务
class TicketTask implements Runnable{
    // 定义票的数量
    private int num = 50;
    // 定义一个无意义的锁对象
    private final Object obj = new Object();
    @Override
    public void run() {
        while(true){
            // 使用同步代码块
            synchronized (obj) {
                if (num <= 0) {
                    break;
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String name = Thread.currentThread().getName();
                System.out.println(name + "正在售卖编号为【" + num + "】的票");
                num--;
            }
        }
    }
}
